from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from app.models import Activity, NetworkVolumeObservation
from datetime import datetime
import hashlib
from app.services.network_volume.providers.douyin_api import fetch_douyin_account_metrics, fetch_douyin_keyword_series


async def collect_douyin(session: AsyncSession, activity_id: str, keywords: list[str] | None = None, accounts: dict | None = None) -> int:
    act = await session.get(Activity, activity_id)
    if not act:
        return 0
    count = 0
    accs = []
    if accounts and isinstance(accounts.get('douyin'), list):
        accs = [str(x) for x in accounts.get('douyin')]
    for acc in accs:
        metrics = await fetch_douyin_account_metrics(acc)
        for k in ['likes','comments','shares','favorites','impressions']:
            v = float(metrics.get(k, 0) or 0)
            if v <= 0:
                continue
            fp = hashlib.sha256(f'douyin:{acc}:{k}'.encode()).hexdigest()
            obj = NetworkVolumeObservation(
                activity_id=activity_id,
                platform='douyin',
                metric_type=k,
                value=v,
                unit=None,
                observed_at=datetime.utcnow(),
                source_url=None,
                source_title=None,
                author_or_account=acc,
                evidence_id=None,
                fingerprint_hash=fp,
            )
            session.add(obj)
            count += 1
    kws = keywords or [act.name or '']
    for kw in [x for x in kws if x]:
        series = await fetch_douyin_keyword_series(kw)
        total = 0.0
        for item in series:
            total += float(item.get('value', 0) or 0)
        if total > 0:
            fp = hashlib.sha256(f'douyin:{kw}:impressions'.encode()).hexdigest()
            obj = NetworkVolumeObservation(
                activity_id=activity_id,
                platform='douyin',
                metric_type='impressions',
                value=total,
                unit=None,
                observed_at=datetime.utcnow(),
                source_url=None,
                source_title=None,
                author_or_account=kw,
                evidence_id=None,
                fingerprint_hash=fp,
            )
            session.add(obj)
            count += 1
    await session.flush()
    await session.commit()
    return count
